package com.ywjt.platformbusiness.store.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.base.BaseModel;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.store.adapter.StoreAddGoods1Adapter;
import com.ywjt.platformbusiness.store.model.SkuModel2;
import com.ywjt.platformbusiness.util.GlideEngine;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.ToastUtil;
import com.ywjt.platformbusiness.widget.CenterDialogEdit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class StoreAddGoodsActivity extends BaseActivity  implements View.OnClickListener {
    private RecyclerView rcDetailPic,rcCommon;
    private EditText etGoodsName;
    private ImageView ivGoodsMainPic,ivClear;
    private LinearLayout llGoodsType,llAdd;
    private TextView tvGoodsType,tvUpGoods;
    private static final Integer REQUESTCODE=10001;
    private static final Integer REQUESTCODE2=10002;

    private String name="";//商品名称
    private String mainPhoto="";//商品主图
    private String goodsTypeId="";//商品分类
    private String detailPhoto="";//商品详情图

    private AddImageAdapter adapter;
    private ArrayList<String> imagesUrl;
    private RecyclerView.LayoutManager managers;
    private StoreAddGoods1Adapter goods1Adapter;

    private List<SkuModel2> goods1;
    private List<SkuModel2.GoodsSkuVOListDTO> goodsSkuVOList;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, StoreAddGoodsActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.store_addgoods_activity;
    }

    @Override
    protected void initView() {
        setTitleText("添加商品");
        ivGoodsMainPic=findViewById(R.id.ivGoodsMainPic);
        llGoodsType=findViewById(R.id.llGoodsType);
        rcDetailPic=findViewById(R.id.rcDetailPic);
        ivClear=findViewById(R.id.ivClear);
        rcCommon=findViewById(R.id.rcCommon);
        tvUpGoods=findViewById(R.id.tvUpGoods);
        llAdd=findViewById(R.id.llAdd);
        tvGoodsType=findViewById(R.id.tvGoodsType);
        etGoodsName=findViewById(R.id.etGoodsName);
        ivClear.setOnClickListener(this::onClick);
        llAdd.setOnClickListener(this::onClick);
        ivGoodsMainPic.setOnClickListener(this::onClick);
        tvUpGoods.setOnClickListener(this::onClick);
        llGoodsType.setOnClickListener(this::onClick);
        etGoodsName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                name=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        imagesUrl=new ArrayList<>();
        managers=new GridLayoutManager(getContext(),3);
        rcDetailPic.setLayoutManager(managers);
        adapter=new AddImageAdapter(imagesUrl, StoreAddGoodsActivity.this);
        rcDetailPic.setHasFixedSize(true);
        rcDetailPic.setAdapter(adapter);
        adapter.setClickListener(new AddImageAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                //添加
                PictureSelector
                        .create(StoreAddGoodsActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.MULTIPLE)
                        .isCamera(true)
                        .maxSelectNum(3)
                        .compressQuality(100)
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void onSelected(View view, int position) {
                switch (view.getId()){
                    case R.id.ivClear:
                        //删除当前图片
                        imagesUrl.remove(position);
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        });

        goods1=new ArrayList<>();
        goods1Adapter=new StoreAddGoods1Adapter(goods1);
        rcCommon.setLayoutManager(new LinearLayoutManager(StoreAddGoodsActivity.this));
        rcCommon.setAdapter(goods1Adapter);
        goods1Adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()){
                    case R.id.ivDel:
                        goods1.remove(position);
                        goods1Adapter.notifyDataSetChanged();
                        break;
                    case R.id.llSkuSelect:
                        Intent intent=new Intent(StoreAddGoodsActivity.this, ActivityGoodsSku.class);
                        intent.putExtra("flag", REQUESTCODE2);
                        intent.putExtra("index",position);
                        startActivityForResult(intent, REQUESTCODE2);
                        break;
                    case R.id.tvPrice:
                        CenterDialogEdit dialogEdit=new CenterDialogEdit(StoreAddGoodsActivity.this,"价格","");
                        dialogEdit.setClicklistener(new CenterDialogEdit.ClickListenerInterface() {
                            @Override
                            public void confirm(String price) {
                                goods1.get(position).setPrice(Integer.parseInt(price));
                                goods1Adapter.notifyDataSetChanged();
                                dialogEdit.dismiss();
                            }
                        });
                        dialogEdit.show();
                        break;
                    case R.id.tvStock:
                        CenterDialogEdit stockEdit=new CenterDialogEdit(StoreAddGoodsActivity.this,"库存","");
                        stockEdit.setClicklistener(new CenterDialogEdit.ClickListenerInterface() {
                            @Override
                            public void confirm(String price) {
                                goods1.get(position).setStock(price);
                                goods1Adapter.notifyDataSetChanged();
                                stockEdit.dismiss();
                            }
                        });
                        stockEdit.show();
                        break;
                }
            }
        });
    }

    @Override
    protected void initData() { }

    private String path="";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
             if (requestCode==PictureConfig.CHOOSE_REQUEST) {
                // 结果回调 获取oss  token
                List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
                imagesUrl.clear();
                for (int i = 0; i < cameraList.size(); i++) {
                    imagesUrl.add(cameraList.get(i).getRealPath());
                }
                adapter.notifyDataSetChanged();
            }else if (requestCode==REQUESTCODE){
                goodsTypeId=data.getStringExtra("id");
                tvGoodsType.setText(data.getStringExtra("name"));
            }else if(requestCode==REQUESTCODE2){
                 goodsSkuVOList=(List<SkuModel2.GoodsSkuVOListDTO>)data.getSerializableExtra("goodsSkuVOList");
               int  index=data.getIntExtra("index",0);
               goods1.get(index).setGoodsSkuVOList(goodsSkuVOList);
                 goods1Adapter.notifyDataSetChanged();
             }else if (requestCode==PictureConfig.REQUEST_CAMERA){
                 List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
                 path=cameraList.get(0).getRealPath();
                 Glide.with(StoreAddGoodsActivity.this).load(path)
                         .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
                         .into(ivGoodsMainPic);
                 ivClear.setVisibility(View.VISIBLE);
                 uploadImg(path);
             }
        }
    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llAdd:
                SkuModel2 model=new SkuModel2();
                model.setPrice(0);
                model.setStock("0");
                List<SkuModel2.GoodsSkuVOListDTO> list=new ArrayList<>();
                model.setGoodsSkuVOList(list);
                goods1.add(model);
                goods1Adapter.notifyDataSetChanged();
                break;
            case R.id.ivClear:
                //清楚图片
                ivGoodsMainPic.setImageResource(R.mipmap.icon_add_picture);
                mainPhoto="";
                ivClear.setVisibility(View.GONE);
                break;
            case R.id.ivGoodsMainPic:
                //添加主图
                PictureSelector
                        .create(StoreAddGoodsActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.MULTIPLE)
                        .isCamera(true)
                        .maxSelectNum(3)
                        .compressQuality(100)
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .forResult(PictureConfig.REQUEST_CAMERA);
                break;
            case R.id.llGoodsType:
                Intent intent=new Intent(StoreAddGoodsActivity.this, ActivityGoodsType.class);
                intent.putExtra("flag", REQUESTCODE);
                startActivityForResult(intent, REQUESTCODE);
                break;
            case R.id.tvUpGoods:
                //上传商品
                if (name.equals("")){
                    Toast.makeText(StoreAddGoodsActivity.this,"请填写商品名称",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (goodsTypeId.equals("")){
                    Toast.makeText(StoreAddGoodsActivity.this,"请选择商品分类",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (goodsSkuVOList.size()<1){
                    Toast.makeText(StoreAddGoodsActivity.this,"请添加商品规格",Toast.LENGTH_SHORT).show();
                    return;
                }

                if (detailPhoto.length()<1){
                    if (imagesUrl.size()<1){
                        Toast.makeText(StoreAddGoodsActivity.this,"请添加商品详情图片",Toast.LENGTH_SHORT).show();
                        return;
                    }else {
                        uploadImgs(imagesUrl.get(0));
                    }
                }else {
                    addGoods();
                }
                break;
        }
    }

    public void uploadImg(String path){
        new HttpRequest(StoreAddGoodsActivity.this).doUploadFile(UrlConstants.common_upload, "", "file", new File(path), new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model=(BaseModel) obj;
                            mainPhoto=model.getMessage();
                            }
                        }else {
                            ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                            toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }


    public void uploadImgs(String path){
        new HttpRequest(StoreAddGoodsActivity.this).doUploadFile(UrlConstants.common_upload, "", "file", new File(path), new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model=(BaseModel) obj;
                            imagesUrl.remove(0);
                            detailPhoto=detailPhoto+model.getMessage()+",";
                            Iterator<String> iterator=imagesUrl.iterator();
                            if (iterator.hasNext()){
                                uploadImg(iterator.next());
                            }else {
                                addGoods();
                            }
                        }else {
                            ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                            toastUtil.show();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }


    //添加商品
    public void addGoods(){
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("mainPhoto",mainPhoto);//商品主图
            jsonObject.put("name",name);//商品名称
            jsonObject.put("categoryId",goodsTypeId);//商品分类
            jsonObject.put("detailPhoto",detailPhoto.substring(0,detailPhoto.length()-1));//商品详情图
            jsonObject.put("status","0");
            JSONArray jsonArray=new JSONArray();
            for (int i=0;i<goods1.size();i++){
                JSONObject p=new JSONObject();
                p.put("skuPrice",goods1.get(i).getPrice());
                p.put("stock",goods1.get(i).getStock());

                JSONArray jsonArray1=new JSONArray();
                for (int j=0;j<goods1.get(i).getGoodsSkuVOList().size();j++){
                    JSONObject json=new JSONObject();
                    json.put("key",goods1.get(i).getGoodsSkuVOList().get(j).getKey());
                    json.put("value",goods1.get(i).getGoodsSkuVOList().get(j).getValue());
                    jsonArray1.put(json);
                }
                p.put("goodsSkuVOList",jsonArray1);
                jsonArray.put(p);
            }

            jsonObject.put("goodsSkuList",jsonArray);//sku列表
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(getContext()).doPost(UrlConstants.commodity_addCommodity, "", jsonObject,new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }
}
